package com.framework.bdf4j.sysadm.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.persist.PageDomain;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.util.StringUtils;
import com.framework.bdf4j.comm.util.TreeUtils;
import com.framework.bdf4j.sysadm.entity.SysDept;
import com.framework.bdf4j.sysadm.entity.SysIdepermission;
import com.framework.bdf4j.sysadm.entity.SysRole;
import com.framework.bdf4j.sysadm.entity.SysUserRole;
import com.framework.bdf4j.sysadm.mapper.SysUserRoleMapper;
import com.framework.bdf4j.sysadm.service.SysDeptService;
import com.framework.bdf4j.sysadm.service.SysIdepermRoleService;
import com.framework.bdf4j.sysadm.service.SysIdepermissionService;
import com.framework.bdf4j.sysadm.service.SysRoleMenuService;
import com.framework.bdf4j.sysadm.service.SysRoleService;
import com.framework.bdf4j.sysadm.vo.Ztree;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;

import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;

@Controller
@AllArgsConstructor
@RequestMapping("/admin/role")
@Api(value = "role", tags = "角色管理模块")
public class SysRoleController {
    private final SysRoleService sysRoleService;
    private final SysDeptService sysDeptService;
    private final SysRoleMenuService sysRoleMenuService;
    
	private final SysIdepermissionService idePermissionService;
	private final SysIdepermRoleService idePermRoleService;
	private final SysUserRoleMapper sysUserRoleMapper;

    // 跳转到角色列表页
    @GetMapping("/index")
    public String goRole() {
        return "sysadm/role/roleList";
    }

    // 跳转到角色编辑页
    @GetMapping("/goEditRole")
    public String goEditRole(@RequestParam(required = false) String id, @RequestParam String oper, Model model) {
        SysRole role = new SysRole();
        if (!"add".equals(oper)) {
            role = sysRoleService.getById(Integer.parseInt(id));
        }
        model.addAttribute("viewobject", role);
        model.addAttribute("oper", oper);
        return "sysadm/role/roleEdit";
    }

    /**
     * 添加角色
     *
     * @param sysRole
     *            角色信息
     * @return success、false
     */
    @SysLog("添加角色")
    @PostMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_role_add')")
    public R save(SysRole sysRole) {
        // 角色编码判重
        List<SysRole> rolelist = sysRoleService.list(Wrappers.<SysRole>query().lambda()
            .eq(SysRole::getRoleCode, sysRole.getRoleCode()).eq(SysRole::getDelFlag, Constants.STATUS_NORMAL));

        if (CollectionUtils.isNotEmpty(rolelist)) {
            return R.failed("角色编码不能重复");
        }
        return R.ok(sysRoleService.save(sysRole));
    }

    /**
     * 修改角色
     *
     * @param sysRole
     *            角色信息
     * @return success/false
     */
    @SysLog("修改角色")
    @PutMapping
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_role_edit')")
    public R update(SysRole sysRole) {
        // 角色编码判重
        List<SysRole> rolelist =
            sysRoleService.list(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode, sysRole.getRoleCode())
                .eq(SysRole::getDelFlag, Constants.STATUS_NORMAL).ne(SysRole::getRoleId, sysRole.getRoleId()));

        if (CollectionUtils.isNotEmpty(rolelist)) {
            return R.failed("角色编码不能重复");
        }
        sysRole.setUpdateTime(new Date());
        return R.ok(sysRoleService.updateById(sysRole));
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @SysLog("删除角色")
    @DeleteMapping("/{id}")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_role_del')")
    public R removeById(@PathVariable Integer id) {
    	Integer count = sysUserRoleMapper.selectCount(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,id));
    	if(count > 0) {
    		return R.failed("当前角色下存在用户");
    	}
    	sysUserRoleMapper.delete(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,id));
        return R.ok(sysRoleService.removeRoleById(id));
    }

    /**
     * 分页查询角色信息
     *
     * @param page
     *            分页对象
     * @return 分页对象
     */
    @GetMapping("/page")
    @ResponseBody
    public R getRolePage(Page page, PageDomain domain, SysRole sysrole) {
        OrderItem orderitem = StringUtils.getOrderItem(domain);
        if (orderitem != null) {
            page.addOrder(orderitem);
        }
        return R.ok(sysRoleService.page(page, Wrappers.query(sysrole)));
    }

    /**
     * 导出Excel文件
     *
     */
    @GetMapping("/export")
    public void doExcel(HttpServletResponse response, SysRole sysrole) {
        Workbook workbook = DefaultExcelBuilder.of(SysRole.class).build(sysRoleService.list(Wrappers.query(sysrole)));
        AttachmentExportUtil.export(workbook, "角色数据", response);
    }

    /**
     * 更新角色菜单
     *
     * @param roleId
     *            角色ID
     * @param menuIds
     *            菜单ID拼成的字符串，每个id之间根据逗号分隔
     * @return success、false
     */
    @SysLog("更新角色菜单")
    @PostMapping("/menu")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('sys_role_perm')")
    public R saveRoleMenus(Integer roleId, @RequestParam(value = "menuIds", required = false) String menuIds,@RequestParam(value = "idePerms", required = false) String idePerms) {
        SysRole sysRole = sysRoleService.getById(roleId);
        if (menuIds.endsWith("#")) {
            menuIds = menuIds.substring(0, menuIds.length() - 1);
        }
        sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleId, menuIds,idePerms);
        return R.ok();
    }

    // 跳转到角色分配权限页面
    @GetMapping("/goSetPerm/{roleId}")
    public String goSetPerm(@PathVariable String roleId, Model model) {
        model.addAttribute("roleId", roleId);
    	//查询所有的IDE资源权限
		List<SysIdepermission> permlist = idePermissionService.list(new QueryWrapper<SysIdepermission>().orderByAsc("perm_code"));
		//查询当前角色的IDE资源权限
		List<Long> permrolelist = idePermRoleService.selectPermIdByRoleId(Integer.valueOf(roleId));
		for (SysIdepermission pb : permlist) {
			if (permrolelist.contains(pb.getId())) {
				pb.setChecked(true);
			}
		}
    	model.addAttribute("idePermList", permlist);
        return "sysadm/role/rolePerm";
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(@RequestParam String roleId) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = sysDeptService.list(Wrappers.emptyWrapper());
        if (StringUtils.isNotBlank(roleId)) {
            List<String> roleDeptList =
                Arrays.asList(StringUtils.trimToEmpty(sysRoleService.getById(roleId).getDsScope()).split(","));
            ztrees = TreeUtils.initDeptZtree(deptList, roleDeptList);
        } else {
            ztrees = TreeUtils.initDeptZtree(deptList, null);
        }
        return ztrees;
    }
}
